<%--
  Created by IntelliJ IDEA.
  User: HY
  Date: 2020/9/16
  Time: 20:00
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <c:import url="../template/_header.jsp"/>
    <title>新建模板-知了[团队知识管理应用]</title>

    <%--tinymce--%>
    <link href="../assets/vendor/uppy/uppy.min.css" rel="stylesheet">
    <script src="../assets/vendor/tinymce/tinymce.min.js"></script>
    <script src="../assets/vendor/tinymce/langs/zh_CN.js"></script>
</head>

<body>
<div class="re-main">
    <c:import url="../template/_navbar.jsp"/>
    <button class="box_top hover_box" style="z-index: 2" onclick="goToBottom()">
        <img src="../assets/images/Down.png" height="20" width="20" />
    </button>
    <div class="re-box-6 re-grey mt-85">
        <div class="container">
            <div class="row justify-content-center">
                <div class="col-lg-12 col-xl-12">
                    <div class="re-box-decorated">
                        <div class="re-box-content">
                            <%---------------------- 标题 ----------------------%>
                            <div class="re-form-group">
                                <ul class="re-breadcrumbs pb-40" id="breadCrumb">
                                    <a href="../manage">管理</a>&nbsp;|&nbsp;<a href="javascript:void(0)" onclick="javascript :history.back(-1);">模板管理</a>&nbsp;|&nbsp;新建模板
                                </ul>
                                <span class="mnt-7 font-2"><strong>&nbsp;名&nbsp;称&nbsp;</strong></span>
                                <input type="text"  class="form-control form-control-style-2"
                                       id="title" placeholder="请输入模板名称，内容不可为空">
                            </div>
                            <br/>

                            <%---------------------- 正文编辑 ----------------------%>
                            <div>
                                <div id="templateEditor" autofocus></div>
                            </div>
                            <br/>

                            <%---------------------- 保存 ----------------------%>
                            <div class="re-form-group" style="float:right">
                                <button class="re-btn" type="submit" id="saveTemplate" onclick="checkattachment()"><a class="mnt-7">保&nbsp;存</a></button>
                            </div>
                            <br/>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <button class="box_bottom hover_box" onclick="goToTop()">
        <img src="../assets/images/Up.png" height="20" width="20" />
    </button>


    <c:import url="../template/_footer.jsp"/>
    <!-- END: Footer -->
</div>
</body>

<style>
    .label_style {
        font-family: "Maven Pro", sans-serif;
        font-size: 1rem;
        width: 100%;
        /*font-weight: 500;*/
        /*line-height: 1;*/
    }

    .label_style:hover {
        background-color: #e1e1e1;
    }
</style>

<!-- START: Scripts -->
<c:import url="../template/_include_js.jsp"/>

<%-- tinymce --%>
<script src="../assets/vendor/tinymce/tinymce.min.js"></script>
<script language="JavaScript">
    function goToTop() {
        window.scrollTo(0, 0);
    }
    function goToBottom() {
        window.scrollTo(0, document.documentElement.scrollHeight-document.documentElement.clientHeight);
    }


    /* 加载动画 */
    loading("show");

    /* 富文本编辑器 */
    tinymce.init({
        selector: '#templateEditor',
        contextmenu: "bold copy | link | image | imagetools | table | spellchecker",//上下文菜单
        auto_focus: true,
        menubar: false,
        language: 'zh_CN',
        // force_br_newlines: true,
        // force_p_newlines: false,
        // forced_root_block: "",
        // preformatted: true,
        toolbar_mode: 'sliding',
        branding: false,
        content_style: "img {height:auto;max-width:100%;max-height:100%;}",
        plugins: [
            'powerpaste', // plugins中，用powerpaste替换原来的paste
            'image',
            "autoresize",
            "code",
            "link",
            "charmap",
            "emoticons",
            "table",
            "wordcount",
            "advlist",
            "lists",
            "indent2em",
            "hr",
            "toolbarsticky",
            "textpattern",
            'preview',
            'media'
            //...
        ],
        min_height: 400, //编辑区域的最小高度
        fontsize_formats: "8pt 10pt 12pt 14pt 18pt 24pt 36pt 48pt",
        font_formats: "微软雅黑='微软雅黑';宋体='宋体';黑体='黑体';仿宋='仿宋';楷体='楷体';隶书='隶书';幼圆='幼圆';Andale Mono=andale mono,times;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Symbol=symbol;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Trebuchet MS=trebuchet ms,geneva;Verdana=verdana,geneva;Webdings=webdings;Wingdings=wingdings",
        powerpaste_word_import: 'propmt',// 参数可以是propmt, merge, clear，效果自行切换对比
        powerpaste_html_import: 'propmt',// propmt, merge, clear
        powerpaste_allow_local_images: true,
        paste_data_images: true,

        images_upload_handler: function (blobInfo, success, failure) {
            var xhr, formData;
            xhr = new XMLHttpRequest();
            xhr.withCredentials = false;
            xhr.open("POST", "${pageContext.request.contextPath}/util/uploadImage");
            formData = new FormData();
            formData.append("file", blobInfo.blob(), blobInfo.filename());
            xhr.onload = function (e) {
                var json;
                if (xhr.status != 200) {
                    failure('HTTP Error: ' + xhr.status);
                    return;
                }
                json = JSON.parse(this.responseText);

                if (!json || typeof json.location != 'string') {
                    failure('Invalid JSON: ' + xhr.responseText);
                    return;
                }
                success(json.location);
            };
            xhr.send(formData);
        },
        toolbar: [
            'code insertfile undo redo emoticons | formatselect | forecolor backcolor charmap bold italic underline strikethrough hr | fontselect | fontsizeselect | blockquote subscript superscript removeformat |',
            'bullist numlist | alignleft aligncenter alignright alignjustify outdent indent indent2em | preview link media image table'
        ],
        init_instance_callback: function (editor) {
            <%--console.log("${resource.text}");--%>
            <%--editor.setContent("${fn:replace((fn:replace(template.templateCode,'\\"','"')), '"', '\\"')}");--%>
            loading("reset");
        },
        my_toolbar_sticky: true,
        toolbar_sticky_always: true,
        toolbar_sticky_elem: "nav",
        toolbar_sticky_elem_autohide: false
    });


    /* 提交保存模板 */
    function checkattachment(){
            submit();
    }

    function submit() {
        var name = $("#title").val();
        <%--var id = ${template.id};--%>
        var text = tinyMCE.activeEditor.getContent();

        if (title == "") {
            $.fillTipBox({type: 'danger', icon: 'glyphicon-exclamation-sign', content: '模板名称不可为空'});
            return false;
        } else if (text == "") {
            $.fillTipBox({type: 'danger', icon: 'glyphicon-exclamation-sign', content: '模板正文不可为空'});
            return false;
        } else {

            loading("show");
            <%--//处理\n换行符--%>
            text = text.replaceAll("\n", "");
            $.post("../template/newTemplate", {
                // id: id,
                name: name,
                text: text,
            }, function (data) {
                if (data.msg == 'SUCCESS') {
                    // if (resource != null){
                    //     // window.localStorage.removeItem('resource');// 编辑成功后删除本地缓存的草稿
                    // }
                    $.fillTipBox({type: 'success', icon: 'glyphicon-ok-sign', content: '新建模板成功'});
                    loading("reset");
                                window.location.href = "<%=request.getContextPath()%>/template/templateContent?templateId="+data.templateId;
                } else if (data.msg == '必填项未填写完整') {
                    $.fillTipBox({type: 'danger', icon: 'glyphicon-exclamation-sign', content: '必填项必须填写完成'});
                    loading("reset");
                } else {
                    $.fillTipBox({type: 'error', icon: 'glyphicon-alert', content: '新建模板失败'});
                    // alert("保存失败0.0");
                    loading("reset");
                }
            });
        }
    }

    /* 临时保存资源 */
    var TimeInterval = 6000;
    var time1 =  setInterval(temp_submit, TimeInterval);
    var auto_store;
    function temp_submit() {
        <%--var title = $("#title").val();--%>
        <%--// var group = $("#group").val();--%>
        <%--var id = ${resource.id};--%>
        <%--var text = tinyMCE.activeEditor.getContent();--%>
        <%--var group = groupIds.substring(1);--%>
        <%--var label = labelIds.substring(1);--%>
        <%--var atta = JSON.stringify([{"temp_msg":"temp_submit"}]);  // 不保存附件信息--%>
        <%--var superior = 0;--%>
        <%--var contents = $('#contents').val();--%>
        <%--// 临时存储文章--%>
        <%--window.localStorage.setItem('resource', JSON.stringify({'userId': ${user_id}, 'resourceId': ${resource.id},--%>
        <%--    'title': title, 'text': text}));--%>

        /*
        if (title == "") {
            //$.fillTipBox({type: 'danger', icon: 'glyphicon-exclamation-sign', content: '资源标题不可为空'});
            return false;
        } else if (text == "") {
            //$.fillTipBox({type: 'danger', icon: 'glyphicon-exclamation-sign', content: '资源editor不可为空'});
            return false;
        } else {
            //loading("show");
            <%--//处理\n换行符--%>
            text = text.replaceAll("\n", "");
            $.post("../crudres/editdata", {
                id: id,
                title: title,
                group: group,
                label: label,
                text: text,
                attachment: atta,
                superior: superior,
                contents: contents
            }, function (data) {
                if (data.msg == 'SUCCESS') {
                    $.fillTipBox({type: 'success', icon: 'glyphicon-ok-sign', content: '自动保存：成功'});
                    //loading("reset");
                    //window.location.href = "<%=request.getContextPath()%>/resource/resource?id=${resource.id}";
                } else if (data.msg == '必填项未填写完整') {
                    $.fillTipBox({type: 'danger', icon: 'glyphicon-exclamation-sign', content: '自动保存：失败（必填项空缺）'});
                    //loading("reset");
                } else {
                    $.fillTipBox({type: 'error', icon: 'glyphicon-alert', content: '自动保存：失败'});
                    // alert("保存失败0.0");
                    //loading("reset");
                }
            });
        }
        */
    }

    function loadTempResource() {
        <%--let resource = JSON.parse(localStorage.getItem('resource'))--%>
        <%--if (resource != null && resource['userId'] == ${user_id} && resource['resourceId'] == ${resource.id}) {--%>
        <%--    if (resource['title'] != "" || resource['text'] != ""){--%>
        <%--        $.tipModal('confirm', 'warning', '有文章编辑草稿，需要加载吗?', function (result) {--%>
        <%--            if (result == true) {--%>
        <%--                $('#title').val(resource['title']);--%>
        <%--                // $('#title').val('123');--%>
        <%--                // document.getElementById("editor").innerHTML = resource['text'];--%>
        <%--                // document.getElementById("tinymce").innerHTML = '测试一席';--%>
        <%--                tinyMCE.activeEditor.setContent(resource['text']);--%>
        <%--                window.localStorage.removeItem('resource');--%>
        <%--            } else {--%>
        <%--                window.localStorage.removeItem('resource');--%>
        <%--            }--%>
        <%--        });--%>
        <%--    }--%>
        <%--}--%>
    }


    //在所有资源加载完后再加载自动保存资源，以防止富文本编辑器插件未完整加载即操作富文本编辑器造成的空指针bug
    loadTempResource();
</script>
<style>
    .re-btn{
        border-radius: 3px;
    }
</style>
<!-- END: Scripts -->
</html>